﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;

namespace SkypeTranslater
{
	/// <summary>
	/// Interaction logic for SettingsWindow.xaml
	/// </summary>
	public partial class SettingsWindow
	{
		public System.Collections.ObjectModel.ObservableCollection<Group> Groups
		{
			get { return (System.Collections.ObjectModel.ObservableCollection<Group>)GetValue(GroupsProperty); }
			set { SetValue(GroupsProperty, value); }
		}

		// Using a DependencyProperty as the backing store for MyProperty.  This enables animation, styling, binding, etc...
		public static readonly DependencyProperty GroupsProperty =
			DependencyProperty.Register("Groups", typeof(System.Collections.ObjectModel.ObservableCollection<Group>), typeof(SettingsWindow), new PropertyMetadata(null));

		public static RoutedCommand SaveCommand = new RoutedCommand();
		public static RoutedCommand CancelCommand = new RoutedCommand();

		public SettingsWindow(List<Group> groups)
		{
			InitializeComponent();
			if (groups == null)
				throw new ArgumentNullException("groups");

			InitializeCommands();

			this.CommandBindings.Add(new CommandBinding(ApplicationCommands.New, (s, e) =>
			{
				e.Handled = true; NewGroupWindow wind = new NewGroupWindow();
				wind.Owner = this;
				if(wind.ShowDialog()==true)
				{
					Groups.Add(wind.GroupContext);
				}
				if (appBar1.IsOpen)
					appBar1.IsOpen = false;
			}, (s, e) => e.CanExecute = Groups != null));

			Groups = new System.Collections.ObjectModel.ObservableCollection<Group>(groups);
			this.Loaded += new RoutedEventHandler(SettingsWindow_Loaded);
			this.Closing += new System.ComponentModel.CancelEventHandler(SettingsWindow_Closing);
		}

		private void InitializeCommands()
		{
			this.CommandBindings.Add(new CommandBinding(SaveCommand, (s, e) => { e.Handled = true; SaveChanges(); this.DialogResult = true; },
																	(s, e) => { e.CanExecute = this.Groups != null; }));
			this.CommandBindings.Add(new CommandBinding(CancelCommand, (s, e) => { e.Handled = true; this.DialogResult = false; }, (s, e) => { e.CanExecute = true; }));

			btnCancel.Command = CancelCommand;
			btnSave.Command = SaveCommand;
		}

		void SettingsWindow_Closing(object sender, System.ComponentModel.CancelEventArgs e)
		{
			e.Cancel = false;
		}

		private T GetVisualChild<T>(Visual parent) where T : Visual
		{
			T child = default(T);
			int numVisuals = VisualTreeHelper.GetChildrenCount(parent);
			for (int i = 0; i < numVisuals; i++)
			{
				Visual v = (Visual)VisualTreeHelper.GetChild(parent, i);
				child = v as T;
				if (child == null)
				{
					child = GetVisualChild<T>(v);
				}
				if (child != null)
				{
					break;
				}
			}
			return child;
		}

		private T FindVisualChild<T>(DependencyObject obj, string name) where T : DependencyObject
		{
			for (int i = 0; i < VisualTreeHelper.GetChildrenCount(obj); i++)
			{
				DependencyObject child = VisualTreeHelper.GetChild(obj, i);
				if (child != null && child is T && (child as FrameworkElement).Name.Equals(name))
					return (T)child;
				else
				{
					T childOfChild = FindVisualChild<T>(child, name);
					if (childOfChild != null)
						return childOfChild;
				}
			}
			return null;
		}

		void SettingsWindow_Loaded(object sender, RoutedEventArgs e)
		{
			Elysium.Theme.ThemeManager.Instance.Light(Elysium.Theme.ThemeManager.Instance.Accent);
			e.Handled = true;

			//Binding binding = new Binding("Groups");
			//binding.Mode = BindingMode.TwoWay;
			//binding.UpdateSourceTrigger = UpdateSourceTrigger.Explicit;

			//this.gridGroups.SetBinding(DataGrid.ItemsSourceProperty, binding);
		}

		private void SaveChanges()
		{
			for (int i = 0; i < gridGroups.Items.Count; i++)
			{
				DataGridRow rowContainer = (DataGridRow)gridGroups.ItemContainerGenerator.ContainerFromIndex(i);
				System.Windows.Controls.Primitives.DataGridCellsPresenter presenter = GetVisualChild<System.Windows.Controls.Primitives.DataGridCellsPresenter>(rowContainer);
				for (int j = 0; j < gridGroups.Columns.Count; j++)
				{
					DataGridCell cell = (DataGridCell)presenter.ItemContainerGenerator.ContainerFromIndex(j);
					CheckBox ch = FindVisualChild<CheckBox>(cell, "chkBox1");
					if (ch == null)
					{
						TextBox text = GetVisualChild<TextBox>(cell);
						BindingExpression be = BindingOperations.GetBindingExpression(text, TextBox.TextProperty);
						if (be != null)
							be.UpdateSource();
					}
					else
					{
						BindingExpression be = BindingOperations.GetBindingExpression(ch, CheckBox.IsCheckedProperty);
						if (be != null)
							be.UpdateSource();
					}
				}
			}
		}
	}
}
